package introse;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class clientManager {

    private List<client> clientList;

    public clientManager() {
        loadClients();
    }

    //Loads all clients from the database
    public final Boolean loadClients() {
        try {
            databaseConn conn = new databaseConn();
            ResultSet clients = conn.sqlRead("SELECT * FROM client");

            List<client> tempClientList = new ArrayList();
            while (clients.next()) {
                tempClientList.add(new client(clients.getInt("clientNumber"), clients.getString("clientName"), clients.getString("clientAddress"), clients.getInt("contactNumber"), clients.getBoolean("isActive")));
            }
            this.clientList = tempClientList;
            return true;
        } catch (SQLException ex) {
        }
        return false;
    }

    public boolean hasClient(String clientName) {
        for (client clnt : clientList) {
            if (clnt.getClientName().trim().toLowerCase().equals(clientName.trim().toLowerCase())) {
                return true;
            }
        }
        return false;
    }

    public List<client> getClients(Boolean isActive) {
        List<client> tempClients = new ArrayList();
        for (client clnt : clientList) {
            if (clnt.getIsActive() == isActive) {
                tempClients.add(clnt);
            }
        }
        return tempClients;
    }

    //Get client from client number
    public client getClient(int clientNumber) {
        for (client clnt : clientList) {
            if (clnt.getClientNumber() == clientNumber) {
                return clnt;
            }
        }
        return null;
    }

    //Add a client
    public Boolean addClient(String name, String address, int contactNumber) {
        databaseConn conn = new databaseConn();
        if (conn.sqlStatement(String.format("INSERT INTO `sashmirgasul`.`client` (`clientName`, `clientAddress`, `contactNumber`, `isActive`) VALUES ('%s', '%s', %d, TRUE);", name, address, contactNumber))) {
            loadClients();
            return true;
        }
        return false;
    }
}
